/**
 * Created by xuan on 15/12/30.
 */
define(function (require, exports, module) {
    var $ = require("jquery");
    var util = require("util");

    var api_prefix = G_CONFIG["api_prefix"]+ "/ydxs/cst-assign/";
    var angular = require("angular");
    require("angular-ui");
    require('global');

    angular.module("app", ["ngUI"])
        .controller("Exportdata", ["$scope", function ($scope) {
            $scope.filename = '';
            $scope.canDownload = false;
            $scope.tipText = '报表正在生成，请耐心等待......';
            var timeout = null;

            function startTask() {
                $.ajax(
                    {
                        url: api_prefix + "export&task_id=" + util.getUrlPara('taskId'),
                        type: 'get',
                        success: function (res) {
                        },
                        error: function (res) {
                            //util.alert('请求失败！');
                        }
                    }
                );
            }

            startTask();

            function polling() {
                $.ajax(
                    {
                        url: api_prefix + "get-export-state&task_id=" + util.getUrlPara('taskId'),
                        type: 'get',
                        success: function (res) {
                            if (res.retCode == "0") {
                                $scope.filename = res.data.name;
                                if (res.data.isfinish) {
                                    clearTimeout(timeout);
                                    $scope.canDownload = true;
                                    $scope.downloadUrl = res.data.url;
                                    $scope.tipText = '报表已生成，文件大小：'+( res.data.fileSize).toFixed(2) + 'MB';
                                    $('.btn').css('background-color', '#ffaa31');
                                } else {
                                    timeout = setTimeout(polling, 10000);
                                }
                            } else {
                                util.alert(res.errMsg||'请求失败！');
                            }

                            $scope.$applyAsync();
                        },
                        error: function (res) {
                            util.alert('请求失败！');
                        }
                    }
                );
            }

            polling();

        }]);
    angular.bootstrap(document, ['app']);
});